<template>
  <div class="uploader">
    <input
      type="file"
      class="file"
      :name="'file'"
      ref="file"
      @change="up"
      accept="image/gif, image/jpeg"
    />
    <div class="cover" v-if="!list[0]">
      <slot></slot>
    </div>

    <div class="cover" v-else>
      <img :src="list[0]" alt="" class="img" ref="img" />
      <i class="iconfont icon-chacha" @click.stop="del"></i>
    </div>
  </div>
</template>

<script>
export default {
  name: "UploadImg",
  data() {
    return {
      list: [],
    };
  },
  methods: {
    // 读取图片数据
    up(el) {
      // 读取文件:
      let reader = new FileReader();
      // 以DataURL的形式读取文件:
      reader.readAsDataURL(el.target.files[0]);
      reader.onload = (res) => {
        this.$set(this.list, 0, res.target.result);
      };
    },

    getAllData() {
      // const formData = new FormData(this.$refs.form);
      // formData.append("stepNum", this.num);
      // console.log(this.formData.has("file" + 2));
      // formData.forEach((value, name) => {
      //   console.log(name, value);
      // });
      const formData = new FormData();
      formData.append("banner", this.$refs.file.files[0]);
      if (this.$refs.file.value == "") {
        return;
      }
      return formData;
    },
    del() {
      this.$refs.file.value = "";
      this.$set(this.list, 0, false);
    },
  },
};
</script>

<style lang="scss" scoped>
.uploader {
  position: relative;
  .file {
    position: absolute;
    opacity: 0;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
  .cover {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f8f8f8;
    overflow: hidden;

    img {
      width: 100%;
    }
    .icon-chacha {
      font-style: normal;
      font-size: 6.6667vw;
      line-height: 6.6667vw;
      position: absolute;
      right: 2%;
      top: 2%;
      background: #eeeeee;
      border-radius: 100%;
      z-index: 1;
    }
  }
}
</style>
